import React, { PureComponent } from 'react';
import { connect } from 'dva';
import styles from './UserManager.less';
import {Card,Button, Table,Form,Modal,Input,Select,Checkbox, Row, Col,Radio ,Divider } from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import moment from 'moment';
import { NewForm } from 're-antd';
import {emailValidate,phoneValidate} from '../../common/utils/stringUtils';
import { loadavg } from 'os';


const RadioGroup = Radio.Group;
const FormItem = Form.Item;
const Option = Select.Option;

var initLoading = false;
var roleSelectData = {};
const columns = [
  {
    title: 'id',
    dataIndex: 'userId',
  },
  {
    title: '登录账号',
    dataIndex: 'username',
  },
  {
    title: '手机',
    dataIndex: 'mobile',
  },
  {
    title: '邮箱',
    dataIndex: 'email',
  },
  {
    title: '更新时间',
    dataIndex: 'createTime',
    sorter: true,
    render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
  },
];


@connect(state => ({
  user: state.user,
}))
@Form.create()
export default class UserManager extends PureComponent {

  state = {
    modalTitle:"修改用户",
    postVisible: false,
    postValue:{},
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'user/fetch',
      payload: {pageIndex:1,pageSize:10},
    });
    if(!initLoading){
      dispatch({
        type:'user/judgePermission',
      }).then((permission)=>{
        if(permission.edit||permission.delete){
          columns.push({
              title: '操作',
              filterDropdownVisible: false,
              render: (text, record, index) => (
                <div>
                  <a onClick={() =>  this.initEditValue(record)} hidden={!permission.edit}>修改</a>
                  <Divider type="vertical" hidden={!permission.edit}/>
                  <a onClick={()=> this.doDelete(record.userId)} hidden={!permission.delete}>删除</a>
                </div>
              ),
              
          });
        }
      });
      dispatch({
        type: 'role/fetchAllRole',
      }).then((res)=>{
        roleSelectData = this.setRoleSelect(res);
      });
      initLoading = true;
    }

  }

  setRoleSelect = (allRoleList)=>{
    if (allRoleList.length==0) return allRoleList;
    const children = [];
    allRoleList.forEach((item)=>{
      children.push(<Col span={8} key={item.roleId}><Checkbox value={item.roleId}>{item.roleName}</Checkbox></Col>);
     
    });    
    return children;
  }

  changePage = (pagination) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'user/fetch',
      payload: {
        pageIndex:pagination.current,
        pageSize:pagination.pageSize
      },
    });
  }

  initNewValue = (flag)=>{
    this.changePostVisible(flag);
    this.setState({
      modalTitle:"新建用户",
      postValue:{
        userId:0,
        status:1,
        roleIdList:[],
      }
    });
  }

  initEditValue = (record)=> {
    this.changePostVisible(true);
    //获取角色权限
    this.props.dispatch({
      type: 'user/fetchUserRole',
      payload:record.userId,
    }).then((res) =>{
      this.setState({
        modalTitle:"修改用户",
        postValue:{
          userId:record.userId,
          username:record.username,
          roleIdList:res,
          password:"",
          email:record.email,
          mobile:record.mobile,
          status:record.status,
        }
      });
    });
  }


  doPost = (value)=>{
      const { dispatch } = this.props;
      return dispatch({
        type: 'user/post',
        payload:value,
      }).then((res) =>{
        this.showResult(res);
        this.changePostVisible();
      });
  }

  doDelete = (userId)=>{
    const { dispatch } = this.props;
    var userIds = [userId];
    const isThis = this;//onOk中拿不到this，这里定义一个变量传值
    Modal.confirm({
      title: '删除用户',
      content: '是否删除该用户?',
      onOk() {
        dispatch({
          type: 'user/delete',
          payload:userIds,
        }).then((res) =>{
            isThis.showResult(res);
            isThis.changePostVisible();  
        });
      },
      onCancel() {},
    });
  }

  changePostVisible = (flag) => {
    if(!!flag===true && this.newform!=undefined){
      this.newform.reset();    
    }
    this.setState({
      postVisible: !!flag,
    });
  }

  showResult = (response)=>{
    if(response.code===200){
      Modal.success({
        title: '成功',
        content: '成功',
      });
      this.props.dispatch({
        type: 'user/fetch',
        payload: {
          pageIndex:this.props.user.data.pagination.pageIndex,
          pageSize:this.props.user.data.pagination.pageSize
        },
      });
    }else{
      Modal.error({
        title: '失败',
        content: '失败',
      });
    }
  }

  export = ()=>{
    alert("*******");
    const { dispatch } = this.props;
    dispatch({
      type: 'user/export',
      payload: {},
    });
  }

  render() {
    const { user: { loading: loading, data ,permission} } = this.props;
    const { postVisible,postValue,modalTitle } = this.state;

    return (
      <PageHeaderLayout>
        <div className={styles.standardTable}>
            <Card bordered={false}>
            <div className={styles.tableList}>
    
              <div className={styles.tableListOperator} hidden={!permission.save}>
                  <Button icon="plus" type="primary" onClick={() => this.initNewValue(true)} >
                    新建
                  </Button>
                  <div className={styles.downloadDiv}>
                  <Button type="primary" icon="download" onClick={() => this.export()}>导出</Button>
                </div>
              </div>

                
              <Table
                loading={loading}
                dataSource={data.list}
                columns={columns}
                rowKey={record => record.userId}
                pagination={data.pagination}
                onChange={this.changePage}
              />
                <Modal
                  title={modalTitle}
                  visible={postVisible}
                  maskClosable={false}                  
                  // onOk={this.doPost}
                  onCancel={() => this.changePostVisible()}
                  footer={null}
                >
                  <NewForm
                    wrappedComponentRef={(v) => this.newform = v}
                    button={
                      [{ text: '确定', type: 'primary', onClick: 'sumbit' },{ text: '取消', onClick: ()=>this.changePostVisible() }]
                    }
                    onSubmit={(value)=>{
                      return this.doPost(value);
                    }}
                    defaultValue={postValue}
                    col={1}
                    items={[
                      {
                        key: 'userId',
                        component: <Input hidden={true} disabled={true}/>,
                      },
                      {
                        rules: [{ required: true, message: '请输入用户名称!' }],
                        key: 'username',
                        label: '用户名',
                        layout:{labelSpan: 5,componentSpan: 15},
                        component: <Input />,
                      },
                      {
                        key: 'password',
                        label: '密码',
                        layout:{labelSpan: 5,componentSpan: 15},
                        component: <Input />,
                      },
                      {
                        rules: [{ required: true, message: '请输入邮件!' },
                                {pattern: emailValidate,message:"您输入的邮箱格式不正确"}
                              ],
                        key: 'email',
                        label: '邮件',
                        layout:{labelSpan: 5,componentSpan: 15},
                        component: <Input />,
                      },
                      {
                        rules: [{ required: true, message: '请输入手机号!' },
                                {pattern: phoneValidate,message:"您输入的手机格式不正确"}
                              ],
                        key: 'mobile',
                        label: '手机号',
                        layout:{labelSpan: 5,componentSpan: 15},
                        component: <Input />,
                      },
                      {
                        rules: [{ required: true, message: '请选择角色!' }],
                        key: 'roleIdList',
                        label: '角色',
                        layout:{labelSpan: 5,componentSpan: 15},
                        component: <Checkbox.Group>
                                        {roleSelectData} 
                                    </Checkbox.Group>,
                      },
                      {
                        key: 'status',
                        label: '状态',
                        layout:{labelSpan: 5,componentSpan: 15},
                        component: <RadioGroup>
                                      <Radio value={1}>正常</Radio>
                                      <Radio value={0}>禁用</Radio>
                                    </RadioGroup>,
                      },
                    ]}
                  />
                </Modal>
            </div>
          </Card>
        </div>
    </PageHeaderLayout>
    );
  }
}
